class Watcher {
  constructor(obj, expression, callback) {
    /**
     * obj,数据对象
     * expression,表达式,如obj.a.b,配合obj取得数据
     * callback,回调
     */
    this.obj = obj
    this.expression = expression
    this.callback = callback

    // 初始化watcher实例的时候订阅数据
    this.state = this.get()
  }

  get() {
    const state = this.getState()
    return state
  }

  update() {
    // 数据发生变化的时候更新
    this.state = this.getState()
    this.callback()
  }

  getState() {
    let state = this.obj
    const segments = this.expression.split('.')
    for (let key of segments) {
      if (!state) return
      state = state[key]
    }
    return state
  }
}